﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using SinacorWebTools.Entity;
using System.Drawing;

namespace SinacorWebTools.Web
{
    public partial class CadastroMenu : BasePage
    {
        #region EVENTS

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                base.SortExpression = string.Empty;
                LoadDataGrid("", "");
            }
        }

        protected void btnPesquisar_Click(object sender, EventArgs e)
        {
            base.SortExpression = string.Empty;
            grdMenu.PageIndex = 0;
            LoadDataGrid(txtPesquisa.Text, hdnModuloPesquisa.Value);
        }

        protected void BtnGravar_Click(object sender, EventArgs e)
        {
            Entity.Menu menu = new SinacorWebTools.Entity.Menu
            {
                Codigo = (TxtCodMenu.Value.Length > 0 ? Convert.ToInt32(TxtCodMenu.Value) : 0),
                Descricao = string.Concat(TxtPreDescricao.Text, TxtDescricao.Text),
                DescricaoAssembly = TxtAssembly.Text,
                DescricaoClasse = TxtClasse.Text,
                Funcao = new Entity.Funcao { CodigoFuncao = (hdnFuncaoSelecionada.Value.Length > 0 ? Convert.ToInt32(hdnFuncaoSelecionada.Value) : 0) },
                CodigoMenuSuperior = (hdnMenuSuperior.Value.Length > 0 ? Convert.ToInt32(hdnMenuSuperior.Value) : 0),
                CodigoSistema = hdnModulo.Value,
                Bloqueado = cboStatus.SelectedValue
            };

            Business.Menu bsMenu = new Business.Menu();
            if (TxtAcao.Value.ToUpper().Equals("I"))
                bsMenu.IncluiMenu(menu);
            else
                bsMenu.AlteraMenu(menu);

            btnPesquisar_Click(this, new EventArgs());
            TxtAssembly.Focus();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "reset", "ResetForm();", true);
        }

        protected void lnk_Click(object sender, EventArgs e)
        {
            int codigoMenu = Int32.Parse(((LinkButton)sender).CommandArgument);
            bool excluiu = new Business.Menu().ExcluiMenu(codigoMenu);

            if (excluiu)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "delete", "alert('Menu excluído com sucesso.'); ResetForm();", true);
                btnPesquisar_Click(this, new EventArgs());
            }
        }

        protected void grdMenu_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            switch (e.Row.RowType)
            {
                case DataControlRowType.Header:

                    ConfigGridViewHeader(grdMenu, e.Row);
                    break;

                case DataControlRowType.DataRow:

                    Entity.Menu m = (e.Row.DataItem as Entity.Menu);

                    LinkButton lnk = (LinkButton)e.Row.FindControl("lnkExcluir");
                    if (lnk != null)
                    {
                        lnk.Click += new EventHandler(lnk_Click);
                        lnk.CommandArgument = m.Codigo.ToString();
                    }

                    LinkButton lnkDescricao = (LinkButton)e.Row.FindControl("lnkDescricao");
                    if (lnkDescricao != null)
                    {
                        m.Funcao = new Business.Funcao().SelecionaFuncaoPorMenu(m.SiglaFuncao);
                        lnkDescricao.Attributes.Add("onclick", "GridItemClick('" + grdMenu.ID + "','" + e.Row.ClientID + "','" + new JavaScriptSerializer().Serialize(m) + "');");
                        lnkDescricao.Attributes.Add("onmouseover", "ShowDiv('dvTraducao'); GetParametrosMensagem('" + m.Descricao + "'); return true;");
                        lnkDescricao.Attributes.Add("onmouseout", "HideDiv('dvTraducao'); return true;");
                        lnkDescricao.Text = m.Descricao;
                    }

                    e.Row.Attributes.Add("onmouseover", "GrifaLinha('#B2BAC6', " + e.Row.ClientID + ");");
                    e.Row.Attributes.Add("onmouseout", "GrifaLinha('#FFFFFF', " + e.Row.ClientID + ");");

                    break;
            }
        }

        protected void grdMenu_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdMenu.PageIndex = e.NewPageIndex;
            LoadDataGrid(txtPesquisa.Text, hdnModuloPesquisa.Value);
        }

        protected void grdMenu_Sorting(object sender, GridViewSortEventArgs e)
        {
            base.SortExpression = e.SortExpression;

            if (base.SortOrder == SortDirection.Ascending)
                base.SortOrder = SortDirection.Descending;
            else
                base.SortOrder = SortDirection.Ascending;

            LoadDataGrid(txtPesquisa.Text, hdnModuloPesquisa.Value);
        }

        #endregion

        #region METHODS

        void LoadDataGrid(string pesquisa, string modulo)
        {
            SortableList<Entity.Menu> menus = new Business.Menu().ListaMenus(pesquisa, modulo);

            if (base.SortExpression.Length > 0)
                menus.Sort(base.SortExpression, (base.SortOrder == SortDirection.Ascending));

            grdMenu.DataSource = menus;
            grdMenu.DataBind();
        }

        [WebMethod]
        public static Dictionary<string, object> GetListaMenuSuperior(string siglaModulo)
        {
            Dictionary<string, object> ret = new Dictionary<string, object>();

            ret.Add("Menu", new Business.Menu().ListaMenuPorModulo(siglaModulo));

            Hashtable hList = new Hashtable();

            for (int item = 0; item < ConfigurationManager.AppSettings.Count; item++)
            {
                if (!ConfigurationManager.AppSettings.AllKeys[item].ToString().ToLower().Contains("string"))
                    hList.Add(ConfigurationManager.AppSettings.AllKeys[item].ToString(), ConfigurationManager.AppSettings[item]);
            }

            ret.Add("Modulo", hList);

            return ret;
        }

        [WebMethod]
        public static List<Entity.Modulo> GetListaModulo()
        {
            return new Business.Modulo().ListaModulos();
        }

        [WebMethod]
        public static Entity.Mensagem GetParametrosMensagem(string resourceKey)
        {
            return new Business.Mensagem().BuscaParametrosMensagem(resourceKey);
        }

        #endregion

        //protected void GrdMenu_RowEditing(object sender, GridViewEditEventArgs e)
        //{
        //    Limpar();

        //    DataSet ds = objMenu.BuscaMenus(int.Parse(((GridView)sender).DataKeys[e.NewEditIndex].Value.ToString()), "", 0, "", "", "", "", "");

        //    TxtAssembly.Text = ds.Tables[0].Rows[0].Field<string>("DS_ASSEMBLY");
        //    TxtClasse.Text = ds.Tables[0].Rows[0].Field<string>("DS_CLASSE");
        //    string descricaoMenu = ds.Tables[0].Rows[0].Field<string>("DS_MENU");
        //    string[] vetDescricaoMenu = descricaoMenu.Split('.');
        //    TxtDescricao.Text = vetDescricaoMenu[vetDescricaoMenu.Count() - 1].ToString();
        //    TxtPreDescricao.Text = descricaoMenu.Replace(TxtDescricao.Text, "");

        //    cboModulo.SelectedValue = ds.Tables[0].Rows[0].Field<string>("CD_SISTEMA");

        //    //CarregaFuncao();
        //    CarregaMenuSuperior();

        //    try
        //    {
        //        hdnFuncaoSelecionada.Value = ds.Tables[0].Rows[0].Field<string>("CD_FUNCAO");
        //    }
        //    catch { }

        //    try
        //    {
        //        cboMenuSuperior.SelectedValue = ds.Tables[0].Rows[0].Field<decimal>("CD_MENUSUP").ToString();
        //    }
        //    catch { }

        //    cboStatus.SelectedValue = ds.Tables[0].Rows[0].Field<string>("IN_BLOQUEIO");
        //    TxtCodMenu.Text = ds.Tables[0].Rows[0].Field<decimal>("CD_MENU").ToString();
        //    TxtAcao.Text = "A";
        //}
    }
}
